<template>
  <el-dialog
    width="22%"
    :title="$t('message.universal.title')"
    :model-value="show"
    @close="close"
  >
    <div>
      <el-input
        v-model="excelName"
        :placeholder="$t('message.excel.placeholder')"
      ></el-input>
    </div>
    <template #footer>
      <el-button @click="close">{{ $t('message.universal.cancel') }}</el-button>
      <el-button @click="confirm" type="primary" :loading="loading">
        {{ $t('message.universal.confirm') }}
      </el-button>
    </template>
  </el-dialog>
</template>
<script setup>
import { ref, defineProps, defineEmits } from 'vue'
import { useI18n } from 'vue-i18n'
import { getUserAll } from '@/api/user-manage'
import { USER_RELATIONS } from './relations'
import { watchLangChange } from '@/utils/i18n'
import { dateFormat } from '@/utils/date'
defineProps({
  show: {
    type: Boolean,
    required: true
  }
})
const i18n = useI18n()
let exportDefaultName = i18n.t('message.excel.defaultName')
const excelName = ref('')
excelName.value = exportDefaultName
watchLangChange(() => {
  exportDefaultName = i18n.t('message.excel.defaultName')
  excelName.value = exportDefaultName
})

const emits = defineEmits(['update:show'])
const close = () => {
  emits('update:show', false)
}
const loading = ref(false)
const confirm = async () => {
  loading.value = true
  const resp = await getUserAll()
  const excel = await import('./Export2Excel.js')
  const data = formatExcel(USER_RELATIONS, resp.list)
  excel.export_json_to_excel({
    header: Object.keys(USER_RELATIONS),
    data,
    fileName: excelName.value || exportDefaultName,
    autoWidth: true,
    bookType: 'xlsx'
  })
  loading.value = false
  close()
}
const formatExcel = (Header, list) => {
  const rows = []
  list.map((item) => {
    const row = []
    Object.keys(Header).map((key) => {
      if (Header[key] === 'role') {
        const roles = item[Header[key]].map((item) => item.title)
        row.push(roles.join(','))
        return
      }
      if (Header[key] === 'openTime') {
        const openTime = dateFormat(item[Header[key]])
        row.push(openTime)
        return
      }
      row.push(item[Header[key]])
    })
    rows.push(row)
  })
  return rows
}
</script>
<style></style>
